# api_test.py
import requests
import json

API_BASE = "http://localhost:5000/api"

def test_health():
    """测试健康检查接口"""
    try:
        response = requests.get(f"{API_BASE}/health")
        print("健康检查:")
        print(json.dumps(response.json(), ensure_ascii=False, indent=2))
        return response.status_code == 200
    except Exception as e:
        print(f"健康检查失败: {e}")
        return False

def test_login_fail():
    """测试错误登录"""
    try:
        data = {"username": "wrong", "password": "wrong"}
        response = requests.post(f"{API_BASE}/login", json=data)
        print("\n错误登录测试:")
        print(f"状态码: {response.status_code}")
        print(json.dumps(response.json(), ensure_ascii=False, indent=2))
        return response.status_code == 401
    except Exception as e:
        print(f"错误登录测试失败: {e}")
        return False

def test_login_success():
    """测试正确登录（需要真实账号）"""
    try:
        # 注意: 这里需要使用真实的账号密码进行测试
        print("\n正确登录测试:")
        print("注意: 请手动替换为真实的账号密码进行测试")
        print("data = {'username': 'A250501576', 'password': '***'}")
        print("测试代码已准备好，请在确认账号密码正确后运行")
        return True
    except Exception as e:
        print(f"正确登录测试失败: {e}")
        return False

if __name__ == "__main__":
    print("=== Flask API 测试 ===")

    # 测试健康检查
    if test_health():
        print("✅ 健康检查通过")
    else:
        print("❌ 健康检查失败")
        exit(1)

    # 测试错误登录
    if test_login_fail():
        print("✅ 错误登录处理正确")
    else:
        print("❌ 错误登录处理异常")

    # 测试正确登录信息
    test_login_success()

    print("\n=== 测试完成 ===")
    print("Flask API 服务器运行正常！")
    print("前端项目地址: http://localhost:3000")
    print("可以在前端页面进行完整登录测试")